const router = require('express').Router()
const validateToken = require('../../../common/validateToken')
const status_code = require('../../../common/status_code')
const db = require('../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../common/bee/bee')

router.post('/comment-like', async (req, resp) => {
  // 错误处理
  function handleError(errCode, error) {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  const { comment_id } = req.body
  if (!Bee.StringUtils.isNumber(comment_id))
    return handleError(10003, '参数错误')

  // 判断是否有该评论
  const [findCommentError, findCommentSuccess] = await to(
    db.query('SELECT count(*) FROM comment WHERE id = ?', [comment_id])
  )
  if (findCommentError || !findCommentSuccess)
    return handleError(-1, findCommentError)
  if (findCommentSuccess[0]['count(*)'] !== 1) handleError(-1, '系统错误') // 没有评论就响应错误

  const [findCommentLikeError, findCommentLikeSuccess] = await to(
    db.query('SELECT count(*) FROM comment_like WHERE comment_id = ?', [
      comment_id,
    ])
  )
  if (findCommentLikeError || !findCommentLikeSuccess)
    return handleError(-1, findCommentLikeError)

  if (findCommentLikeSuccess[0]['count(*)'] === 0) {
    // 没有点过赞
    const [likeError, likeSuccess] = await to(
      db.query(
        'INSERT INTO comment_like (comment_id, user_id, time) VALUES (?, ?, NOW());',
        [comment_id, validateTokenSuccess.id]
      )
    )
    if (likeError || !likeSuccess) return handleError(-1, likeError)

    // 查询点赞数量
    const [findLikeError, findLikeSuccess] = await to(
      db.query(
        'SELECT count(*) FROM comment_like cl, comment c, userinfo ui WHERE cl.comment_id = ? AND cl.comment_id = c.id AND ui.id = cl.user_id;',
        [comment_id]
      )
    )
    if (findLikeError || !findLikeSuccess) return handleError(-1, findLikeError)

    // 更新评论表 praise_num 字段
    const [updateCommentError, updateCommentSuccess] = await to(
      db.query('UPDATE comment SET praise_num = ? WHERE id = ?', [
        findLikeSuccess[0]['count(*)'],
        comment_id,
      ])
    )
    if (updateCommentError || !updateCommentSuccess)
      return handleError(-1, updateCommentError)
    if (likeSuccess.affectedRows > 0) {
      return resp.json({
        code: 0,
        msg: '点赞成功',
        data: {
          count: findLikeSuccess[0]['count(*)'],
        },
      })
    }
  } else {
    // 点过赞 则 取消点赞
    const [delLikeError, delLikeSuccess] = await to(
      db.query('DELETE FROM comment_like WHERE comment_id = ?', [comment_id])
    )
    if (delLikeError || !delLikeSuccess) return handleError(-1, delLikeError)

    // 查询点赞数量
    const [findLikeError, findLikeSuccess] = await to(
      db.query(
        'SELECT count(*) FROM comment_like cl, comment c, userinfo ui WHERE cl.comment_id = ? AND cl.comment_id = c.id AND ui.id = cl.user_id;',
        [comment_id]
      )
    )
    if (findLikeError || !findLikeSuccess) return handleError(-1, findLikeError)

    // 更新评论表 praise_num 字段
    const [updateCommentError, updateCommentSuccess] = await to(
      db.query('UPDATE comment SET praise_num = ? WHERE id = ?', [
        findLikeSuccess[0]['count(*)'],
        comment_id,
      ])
    )
    if (updateCommentError || !updateCommentSuccess)
      return handleError(-1, updateCommentError)
    return resp.json({
      code: 0,
      msg: '取消点赞成功',
      data: {
        count: findLikeSuccess[0]['count(*)'],
      },
    })
  }
})

module.exports = router
